package android.slc.db_room.sys.service;

import android.slc.db_room.sys.entity.CsConfig;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;

import java.util.List;

/**
 * @author slc
 * @date 2024/6/3
 **/
@Dao
public interface CsConfigDao {

    @Insert()
    void insert(CsConfig data);

    @Insert()
    void insert(List<CsConfig> dataList);

    @Update()
    int update(CsConfig data);

    @Delete
    int delete(CsConfig data);

    @Query("delete from cs_config")
    int clearAll();

    @Query("select * from cs_config where id = :id")
    CsConfig getById(Long id);

    @Query("select * from cs_config")
    List<CsConfig> list();

    @Query("select * from cs_config where key = :key limit 1")
    CsConfig getConfig(String key);

    default String getConfigValue(String key) {
        return getConfigValue(key, null);
    }

    default String getConfigValue(String key, String defValue) {
        return getConfigValue(key, defValue, false);
    }

    default String getConfigValue(String key, boolean autoCreate) {
        return getConfigValue(key, null, autoCreate);
    }

    default String getConfigValue(String key, String defValue, boolean autoCreate) {
        CsConfig csConfig = getConfig(key);
        if (csConfig == null && autoCreate) {
            csConfig = new CsConfig();
            csConfig.setKey(key);
            csConfig.setValue(defValue);
            insert(csConfig);
        }
        return csConfig != null ? csConfig.getValue() : defValue;
    }
}
